package summary;

import java.util.LinkedList;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 22:43
 * https://leetcode-cn.com/problems/find-bottom-left-tree-value/
 */
public class Title513 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static int findBottomLeftValue(TreeNode root) {
        LinkedList<TreeNode> list = new LinkedList<>();
        list.offer(root);
        int value = root.val;
        while (!list.isEmpty()) {
            int size = list.size();
            value = list.peek().val;
            for (int i = 0; i < size; i++) {
                TreeNode pop = list.poll();
                if (pop.left != null) {
                    list.offer(pop.left);
                }
                if (pop.right != null) {
                    list.offer(pop.right);
                }
            }
        }
        return value;
    }

    int result, h;

    public int findBottomLeftValue1(TreeNode root) {
        h = -1;
        backingTracking(root, 0);
        return result;
    }

    private void backingTracking(TreeNode root, int height) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            if (height > h) {
                result = root.val;
                h = height;
                return;
            }
        }
        backingTracking(root.left, height + 1);
        backingTracking(root.right, height + 1);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(1);
        root.right = new TreeNode(3);
        findBottomLeftValue(root);
    }
}
